package com.jsg.sl651.message.parser.impl;

import com.jsg.sl651.constant.EncodingElementIdentifier;
import com.jsg.sl651.entity.data.Element;
import com.jsg.sl651.enums.CommunicationMessageType;
import com.jsg.sl651.message.parser.Parser;
import com.jsg.sl651.message.parser.model.EveryFiveMinuteData;
import com.jsg.sl651.util.ByteUtil;

/**
 * 包含一个值一小时内的数据，每5分钟计算一个数字
 */
public class EveryFiveMinutesParser implements Parser<EveryFiveMinuteData> {
    /**
     * 解析Hex模式下的数据
     * <p>方法核心</p>
     * <ul>
     *     <li>解析该字节数组</li>
     *     <li>数据生成相应的数据对象{@link CommunicationMessageType}</li>
     * </ul>
     *
     * @param element 数据类型定义 {@link EncodingElementIdentifier.EncodingElement}
     * @param bytes   字节数组
     * @return 解析出来的数据对象
     */
    @Override
    public Element<EveryFiveMinuteData> parserHexImpl(EncodingElementIdentifier.EncodingElement element, byte[] bytes) throws Exception {
        EveryFiveMinuteData everyFiveMinuteData = parserImpl(bytes, element.getPrecision());
        return new Element<>(bytes, everyFiveMinuteData, element);
    }

    /**
     * 解析Hex模式下的数据
     * <p>方法核心</p>
     * <ul>
     *     <li>解析该字节数组</li>
     *     <li>数据生成相应的数据对象{@link CommunicationMessageType}</li>
     * </ul>
     *
     * @param element 数据类型定义 {@link EncodingElementIdentifier.EncodingElement}
     * @param bytes   字节数组
     * @return 解析出来的数据对象
     */
    @Override
    public Element<EveryFiveMinuteData> parserAsciiImpl(EncodingElementIdentifier.EncodingElement element, byte[] bytes) throws Exception {
        // 如果是ASCII 先将ASCII 转换为HEX
        bytes = ByteUtil.toBytes(bytesToString(bytes));
        EveryFiveMinuteData everyFiveMinuteData = parserImpl(bytes, element.getPrecision());
        return new Element<>(bytes, everyFiveMinuteData,element);
    }



    public static EveryFiveMinuteData parserImpl(byte[] bytes,int precision) throws Exception {
        if (!(bytes.length % 12 == 0)) {
            throw new RuntimeException("数据长度不对,数据长度必须为 12 的整数倍,当前长度： " + bytes.length);
        }
        // 一个数据占的长度
        int length = bytes.length / 12;
        Integer[] finalData = new Integer[12];
        for (int i = 0; i < 12; i++) {
            int index = i * length;
            int sum = 0;
            byte[] data = new byte[length];
            for (int j = 0; j < length; j++) {
                data[j] = bytes[index + j];
            }
            for (int j = 0; j < length; j++) {
                sum += (data[j] & 0xff) << (8 * (length - 1 - j));
            }
            finalData[i] = sum;
        }
        return new EveryFiveMinuteData(finalData,precision);
    }

}
